package sio.slam4;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.h2.engine.Session;
import org.hibernate.Query;

public class Application {
  private static Session s = null;
  private  EntityManagerFactory entityManagerFactory;
  private EntityManager entityManager;
  
  public Application(){
    entityManagerFactory = Persistence
        .createEntityManagerFactory("sio.slam4.tutorial.jpa");
  }
  
  public void go() {
    populate();
    select();
    clear();
    entityManagerFactory.close();
  }


  private  void select() {
    EntityManager entityManager;
    // retrouvons des pays stockés dans la base de données
    entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();
    List<Pays> result = entityManager.createNativeQuery("select * from PAYS", Pays.class)
        .getResultList();
    for (Pays pays : result) {
      System.out.println("Pays (" + pays.getContinent() + ") : "
          + pays.getNom() +" "+ pays.getCapitale().getNom() +"("+pays.getCapitale().getPopulation()+")");
    }

    entityManager.getTransaction().commit();
    entityManager.close();
  }


  private void populate() {
    // creation de quelques pays
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();
    
    entityManager.persist(new Pays("Algérie", "Afrique", "DZ", java.sql.Date
        .valueOf("1962-07-03"),new Ville("Paris", 6000000)));
    entityManager.persist(new Pays("Sénégal", "Afrique", "SN", java.sql.Date
        .valueOf("1960-06-20"),new Ville("Paris", 6000000)));
    entityManager.persist(new Pays("Vietnam", "Asie", "VN", java.sql.Date
        .valueOf("1955-08-16"),new Ville("Paris", 6000000)));
    entityManager.persist(new Pays("États Unis", "Amérique du Nord", "US",
        java.sql.Date.valueOf("1776-07-04"),new Ville("Washington", 6000000)));
    
    entityManager.getTransaction().commit();
    entityManager.close();
  }

  private void clear(){

  }
@Override
protected void finalize() throws Throwable {
  entityManagerFactory.close();
  super.finalize();
}

}